import { MyGameObject } from "./MyGameObject";
// import { Wall } from "./Wall";
// import { Snake } from './Snake';
// import { Food } from "./food";
import { A_GIFS } from "./gif/all_gif";
import $ from "jquery";
import {ElMessage, ElNotification} from "element-plus";
// import { BOMB } from './bomb';

export class GameMap extends MyGameObject { // 游戏地图加入了MYGame
                                    //一帧将会刷新一次，因为其他物品画过后会覆盖，所以地图也要画。                      
    constructor(ctx,parent,store){//构造函数
        super();

        this.ctx = ctx;// 这是canvas
        this.parent = parent;
        this.store = store;
        this.L = 0;

        this.rows = 32;
        this.cols = 32;

        this.inner_wall_counts = 50;
        this.walls = [];//画布上的墙。
        this.walls_pleace = [];//被覆盖的地区，包括food和墙
        this.real_time_map = [];//实时的地图，用来向后端传输。

        this.food = [];//画布上的食物

        this.step_count_a = 0;
        this.step_count_b = 0;//回放功能记录走过步数。


        ////////////////////////////
        this.timeStap = 0;//用于游戏结束时闪烁。
        this.spacing = 20//线的间距
        this.border = 10//边框长度
        this.resultArr = []//记录每一个格子（五子棋的棋盘，初始化为0)
        this.count = 0;
        this.mousex = -20;
        this.mousey = -20;
        this.img = [];
        this.img[0] = new Image(this.L,this.L);//黑
        this.img[1] = new Image(this.L,this.L);//白
        this.img[0].src = "https://cdn.acwing.com/media/article/image/2024/12/28/134627_67d2d12ec4-black.png";//黑棋
        this.img[1].src = "https://cdn.acwing.com/media/article/image/2024/12/28/134627_69f8c68fc4-white.png";//白棋

        this.aiMoveUrl = "http://10.70.128.53:7090/api/ai/move"


        // if(store.state.user.userId == store.state.pk.a_id && !store.state.record.is_record)
        // this.Snake = [
        //     new Snake({userId:store.state.pk.a_id,color:"#4876EC",r:this.rows - 2,c:1},this),
        //     new Snake({userId:store.state.pk.b_id,color:"#F94848",r:1,c:this.cols - 2},this)
        // ];
        // else if(store.state.user.userId == store.state.pk.b_id && !store.state.record.is_record)
        // this.Snake = [
        //     new Snake({userId:store.state.pk.b_id,color:"#4876EC",r:this.rows - 2,c:1},this),
        //     new Snake({userId:store.state.pk.a_id,color:"#F94848",r:1,c:this.cols - 2},this)
        // ];
        // else
        // this.Snake = [
        //     new Snake({userId:store.state.pk.a_id,color:"#4876EC",r:this.rows - 2,c:1},this),
        //     new Snake({userId:store.state.pk.b_id,color:"#F94848",r:1,c:this.cols - 2},this)
        // ];

        this.gif = new A_GIFS();//处理一些GIF
        // console.log(this.store.state.record.is_record);
    }



    checkWin(resultArr) {
        const directions = [
            { dx: 1, dy: 0 },  // 水平
            { dx: 0, dy: 1 },  // 垂直
            { dx: 1, dy: 1 },  // 左斜
            { dx: -1, dy: 1 }  // 右斜
        ];

        for (let y = 0; y < resultArr.length; y++) {
            for (let x = 0; x < resultArr[y].length; x++) {
                if (resultArr[y][x] === 0) continue;

                for (let dir of directions) {
                    let count = 1;
                    let positions = [[x, y]];

                    for (let i = 1; i < 5; i++) {
                        let nx = x + dir.dx * i;
                        let ny = y + dir.dy * i;

                        if (nx < 0 || nx >= resultArr[0].length || ny < 0 || ny >= resultArr.length) break;
                        if (resultArr[ny][nx] !== resultArr[y][x]) break;

                        count++;
                        positions.push([nx, ny]);
                    }

                    if (count === 5) {
                        return {
                            winner: resultArr[y][x],
                            winningPositions: positions
                        };
                    }
                }
            }
        }

        return "-10"; // 没有胜利者
    }


    add_a_point(i,j,isBlack){
        if(this.resultArr[i][j] !== 0) {
            console.log("这个点有棋子");
            return;
        }//这个点有棋子了

        if(isBlack)
        this.resultArr[i][j] = -1;//黑为-1
        else
        this.resultArr[i][j] = 1;//白为1
        this.count ++;//记录棋盘有一个棋子，优化渲染速度

        if(this.store.state.pk.localHostPk){
            let data = this.checkWin(this.resultArr);
            if(data === "-10")
            this.store.commit("updateIAmBlack",!this.store.state.pk.iAmBlack);
            else {
                let k = 0;
                if(this.resultArr[data.winningPositions[0][1]][data.winningPositions[0][0]] === -1)
                    k = 3;
                else if(this.resultArr[data.winningPositions[0][1]][data.winningPositions[0][0]] === 1)
                    k = 5;
                this.timestamp = Date.now();
                for(let i = 0 ; i < 5;i++){
                    this.resultArr[data.winningPositions[i][1]][data.winningPositions[i][0]] = k;
                }
                setTimeout(() => {
                    if (data.winner === -1){
                        this.store.commit("updateLoser","black");
                    }
                    else if(data.winner === 0){
                        this.store.commit("updateLoser","all");
                    }
                    else if(data.winner === 1){
                        this.store.commit("updateLoser","white");
                    }
                }, 1000); // 延迟
            }
        }

    }
    remove_a_point(i,j){
        if(this.store.state.record.is_record){
                this.resultArr[i][j] = 0;
            this.count --;//记录棋盘有一个棋子，优化渲染速度
        }
    }


    add_listening_events(){ //读取输入
        this.ctx.canvas.focus();
        console.log("kkkkkk")
        this.ctx.canvas.addEventListener("mousemove",e=>{
            // console.log(e.offsetX,this.L);
            this.mousex = e.offsetX;
            this.mousey = e.offsetY;

        })
        this.ctx.canvas.addEventListener("mousedown",e=>{
            if(this.store.state.pk.is_me){
                let xx = e.offsetX * 10 / this.L;
                let yy = e.offsetY * 10 / this.L;
                                // 棋盘参数
                const border = 10; // 边框宽度
                const lineCount = 16; // 横竖线条数
                const spacing = 20; // 每条线之间的间隔
                // 遍历所有交叉点
                for (let i = 0; i < lineCount; i++) {
                    for (let j = 0; j < lineCount; j++) {
                        // 每个交叉点的位置
                        let pointX = border + i * spacing;
                        let pointY = border + j * spacing;

                        // 判断 xx, yy 是否在当前交叉点加减3范围内
                        if (Math.abs(xx - pointX) <= 5 && Math.abs(yy - pointY) <= 5) {
                            // console.log(JSON.stringify({
                            //     event: "GAME_MOVE_EVENT",
                            //     data:{
                            //         roomId: this.store.state.pk.roomId,
                            //         userId: this.store.state.user.userId,
                            //         row:i,
                            //         col:j,
                            //     },
                            //     senderId:this.store.state.user.userId,
                            //     timestamp:Date.now(),
                            //
                            // }));//调试
                            if(this.resultArr[i][j] !== 0 || this.store.state.pk.Loser !== "none") {

                                console.log("这个点有棋子或游戏已结束");

                            }//这个点不能下
                            else{
                                if(this.store.state.pk.botId !== "-1"){
                                    this.store.state.pk.is_me = false;//关掉我的下棋权限
                                    const _this = this;
                                    this.add_a_point(i,j,this.store.state.pk.iAmBlack);//落子

                                    const notificationInstance = ElNotification({
                                        title: 'Custom Position',
                                        message: "AI正在思考中",
                                        position: 'bottom-right',
                                        showClose: false,
                                        duration:0,
                                    })
                                    $.ajax({
                                        type: "post",
                                        url: this.aiMoveUrl,
                                        headers:{
                                            Authorization: "Bearer " + this.store.state.user.token//授权
                                        },
                                        contentType: "application/json", // 设置请求头
                                        data: JSON.stringify({
                                            mode:this.store.state.pk.botId,
                                            board:this.resultArr,
                                            row:i,
                                            col:j,
                                            aiColor:this.store.state.pk.iAmBlack?1:-1
                                        }),
                                        success(resp) {
                                            setTimeout(() => {
                                                notificationInstance.close();
                                            }, 1000); // 延迟
                                            ///开始判断AI对战局势
                                            if(resp.data.resultCode === 2 || resp.data.resultCode === -1){
                                                _this.add_a_point(resp.data.aiDecitionPosition.row,resp.data.aiDecitionPosition.col,!_this.store.state.pk.iAmBlack);//落子
                                            }//貌似无论怎么说都要更新ai落的子
                                            if(resp.data.resultCode === 2) {
                                                _this.store.state.pk.is_me = true;//打开我的下棋权限
                                            }
                                            else if(resp.data.resultCode === 1 || resp.data.resultCode === -1){
                                                let k = 0;
                                                if(_this.resultArr[resp.data.winPosList[0][0]][resp.data.winPosList[0][1]] === -1)
                                                    k = 3;
                                                else if(_this.resultArr[resp.data.winPosList[0][0]][resp.data.winPosList[0][1]] === 1)
                                                    k = 5;
                                                _this.timestamp = Date.now();
                                                for(let i = 0 ; i < 5;i++){
                                                    _this.resultArr[resp.data.winPosList[i][0]][resp.data.winPosList[i][1]] = k;
                                                }
                                                if(resp.data.resultCode === -1){
                                                    setTimeout(() => {
                                                        _this.store.commit("updateLoser","you")
                                                    }, 2000); // 延迟
                                                }
                                                else if(resp.data.resultCode === 1){
                                                    setTimeout(() => {
                                                        _this.store.commit("updateLoser","he")
                                                    }, 2000); // 延迟
                                                }
                                            }
                                            else if(resp.data.resultCode === 0){
                                                _this.store.commit("updateLoser","all")
                                            }

                                        },
                                        error(resp){
                                            notificationInstance.close();
                                            ElMessage.error(resp);
                                        }
                                    });

                                }
                                else if(this.store.state.pk.localHostPk){
                                    this.add_a_point(i,j,this.store.state.pk.iAmBlack);//落子

                                }
                                else if(this.store.state.websocket.socket !== null){
                                    this.store.state.pk.is_me = false;//关掉我的下棋权限
                                    this.store.state.websocket.socket.send(JSON.stringify({
                                        event: "GAME_MOVE_EVENT",
                                        data:{
                                            roomId: this.store.state.pk.roomId,
                                            userId: this.store.state.user.userId,
                                            row:i,
                                            col:j,
                                        },
                                        senderId:this.store.state.user.userId,
                                        timestamp:Date.now(),
                                    }))
                                    this.add_a_point(i,j,this.store.state.pk.iAmBlack);//落子
                                }
                            }
                            return; // 找到一个交叉点后可以返回，避免重复处理
                        }
                    }
                }
            }
        })
    }

    updateStep(way){//0是上一步，1是下一步
        if(way === 0){
            if(this.store.state.record.stepCount>0){
                this.store.commit("updateStepCount",this.store.state.record.stepCount - 1)
                this.store.commit("updateIsBlackStep",!this.store.state.record.isBlackStep);
                this.remove_a_point(this.store.state.record.steps[this.store.state.record.stepCount][0],this.store.state.record.steps[this.store.state.record.stepCount][1]);
            }
        }
        else if(way === 1){
            if(this.store.state.record.stepCount < this.store.state.record.steps.length){
                this.add_a_point(this.store.state.record.steps[this.store.state.record.stepCount][0],this.store.state.record.steps[this.store.state.record.stepCount][1],this.store.state.record.isBlackStep);
                this.store.commit("updateStepCount",this.store.state.record.stepCount + 1);
                this.store.commit("updateIsBlackStep",!this.store.state.record.isBlackStep);
            }
        }
    }
    start(){

        // this.create_walls();
        // if(this.store.state.pk.botId === -1)
        if(this.store.state.pk.botId !== "-1" || this.store.state.pk.localHostPk){
            this.store.commit("updateIsMe",true);
        }
        for (let i = 0; i < 16; i++) {
            this.resultArr.push(new Array(16).fill(0));//初始化数组
        }

        if(this.store.state.record.is_record){
            // this.add_listening_events();
            // let k =0;
            //     setInterval(() => {
            //         if(this.Snake[0].status === "die" || this.Snake[1].status === "die"){
            //             return;
            //         }

            //         if(this.store.state.record.food_x[k] !== null && this.store.state.record.food_y[k] !== null &&this.store.state.record.food_x[k] !== undefined && this.store.state.record.food_y[k] !== undefined)
            //             {
            //                 // this.add_food(this.store.state.record.food_x[k],this.store.state.record.food_y[k]);
            //                 k++;
            //             }
            // }, 3000);


            //     setTimeout( ()=> {
                    
            //     }, 1000);
            //         this.Snake[0].status = "move";
            //         this.Snake[1].status = "move";  
        }
        else
        this.add_listening_events();

    }

    update_size() {
        this.L = parseInt(Math.min(this.parent.clientWidth / this.cols,this.parent.clientHeight / this.rows));//计算画布的单位长度（依据当前播放设备动态计算）
        this.ctx.canvas.width = this.L * this.cols;//画布长
        this.ctx.canvas.height = this.L * this.rows;// 画布宽
    }
    update(){
        this.update_size();
        this.render();
    }

    render(){//画画布（16*16的棋盘）
        let _this = this;

        let space = this.L * 0.1;
        _this.ctx.beginPath();
        _this.ctx.fillStyle = "#fff";
        _this.ctx.rect(0, 0, 320 * space, 320 * space);
        _this.ctx.fill();

        for (let i = 0; i < 16; i++) {
            _this.ctx.beginPath();
            _this.ctx.strokeStyle = "#D6D1D1";
            _this.ctx.moveTo(10 * space + i * 20 * space, 10 * space); //垂直方向画16根线，相距30px;
            _this.ctx.lineTo(10 * space + i * 20 * space, 310 * space);
            _this.ctx.stroke();
            _this.ctx.moveTo(10 * space, 10 * space + i * 20 * space); //水平方向画16根线，相距30px;
            _this.ctx.lineTo(310 * space, 10 * space + i * 20 * space);
            _this.ctx.stroke();
        }
        let coinCount = this.count;
        // console.log(coinCount,_this.resultArr);
        for (let i = 0 ; i < 16; i++){
            for(let j = 0 ; j < 16 ;j++){
                if(coinCount < 0 ){
                    break;
                }
                if(_this.resultArr[i][j] === -1){
                    _this.ctx.drawImage(this.img[0],(this.border + i * this.spacing)*this.L/10 - this.L,(this.border + j * this.spacing)*this.L/10 - this.L,this.L*2,this.L*2)
                    coinCount--;
                }
                else if(_this.resultArr[i][j] === 1){
                    _this.ctx.drawImage(this.img[1],(this.border + i * this.spacing)*this.L/10 - this.L,(this.border + j * this.spacing)*this.L/10 - this.L,this.L*2,this.L*2)
                    coinCount--;
                }
                else if(_this.resultArr[i][j] === 3){
                    _this.ctx.drawImage(this.img[0],(this.border + i * this.spacing)*this.L/10 - this.L,(this.border + j * this.spacing)*this.L/10 - this.L,this.L*2,this.L*2)
                    coinCount--;
                    if(Date.now() - this.timeStap > 500){
                        _this.resultArr[i][j] = 4;
                    }

                }
                else if(_this.resultArr[i][j] === 4){
                    coinCount--;
                    if(Date.now() - this.timeStap > 500){
                        _this.resultArr[i][j] = 3;
                    }

                }
                else if(_this.resultArr[i][j] === 5){
                    _this.ctx.drawImage(this.img[1],(this.border + i * this.spacing)*this.L/10 - this.L,(this.border + j * this.spacing)*this.L/10 - this.L,this.L*2,this.L*2)
                    coinCount--;
                    if(Date.now() - this.timeStap > 500){
                        _this.resultArr[i][j] = 6;
                    }

                }
                else if(_this.resultArr[i][j] === 6){
                    coinCount--;
                    if(Date.now() - this.timeStap > 500){
                        _this.resultArr[i][j] = 5;
                    }

                }

            }
        }
        if(Date.now() - this.timeStap > 500){
            this.timeStap = Date.now();
        }
        // _this.ctx.beginPath(); // 开始新路径
        _this.ctx.globalAlpha = 0.5;//设置全局透明度，画完后必须立马改
        if(_this.store.state.pk.iAmBlack)
        _this.ctx.drawImage(this.img[0], this.mousex - this.L, this.mousey - this.L,this.L*2,this.L*2);
        else
        _this.ctx.drawImage(this.img[1], this.mousex - this.L, this.mousey - this.L,this.L*2,this.L*2);
        // console.log(space);
        _this.ctx.globalAlpha = 1;

    }
}